package cn.itcast.service.impl;

import cn.itcast.dao.PermissionDao;
import cn.itcast.dao.RoleDao;
import cn.itcast.dao.UserDao;
import cn.itcast.entity.PageResult;
import cn.itcast.pojo.Permission;
import cn.itcast.pojo.Role;
import cn.itcast.pojo.User;
import cn.itcast.service.UserService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    /**
     * 查询用户消息
     * @param currentPage
     * @param pageSize
     * @param queryString
     * @return
     */
    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;


    /**
     * 根据用户名查询数据库中获取用户信息和关联的角色信息,同时需要擦或许用户关联权限信息
     * @param username
     * @return
     */
    @Override
    public User findByName(String username) {
        User byName = userDao.findByName(username);
        if(byName==null){
            return null;
        }
        Integer id = byName.getId();
        //根据用户id查询角色
        Set<Role> byUserId = roleDao.findByUserId(id);
        byName.setRoles(byUserId);
        for (Role role : byUserId) {
            //根据角色id查询管理权限
            Integer id1 = role.getId();
            Set<Permission> byRoleId = permissionDao.findByRoleId(id1);
            role.setPermissions(byRoleId);//让用户关联权限
        }
        byName.setRoles(byUserId);
        return byName;
    }

    @Override
    public List<Integer> findRoleIdsById(Integer userId) {
        return   this.userDao.findRoleIdsById(userId);
    }

    /**
     * 查询登录的用户名
     * @param username
     * @return
     */
    @Override
    public String findByUserName(String username) {

        return  userDao.findByUserName(username);
    }
}
